<!--
 * @Author: Betty
 * @Date: 2020-11-18 22:16:27
 * @LastEditors: Betty
 * @LastEditTime: 2021-01-06 22:24:13
 * @Description: 登录页
-->
<template>
  <div class="login-page">
    <validate-form @form-submit="onFormSubmit" ref="loginFormRef">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <validate-input
          :rules="emailRules" v-model="emailVal"
          placeholder="请输入邮箱地址"
          type="text"
          ref="inputRef"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">密码</label>
        <validate-input
          type="password"
          placeholder="请输入密码"
          :rules="passwordRules"
          v-model="passwordVal"
        />
      </div>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// eslint-disable-next-line no-unused-vars
import { GlobalDataProps } from '../store'
// eslint-disable-next-line no-unused-vars
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'

export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm
  },
  setup() {
    const emailVal = ref('')
    // 调用钩子函数useRouter，来定义路由的行为
    // eslint-disable-next-line no-unused-vars
    const router = useRouter()
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' }
    ]
    const passwordVal = ref('')
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空' }
    ]
    const loginFormRef = ref<any>()
    // 使用store
    // eslint-disable-next-line no-unused-vars
    const store = useStore<GlobalDataProps>()
    // 触发表单组件的自定义提交事件后
    const onFormSubmit = (result: boolean) => {
      // 如果通过验证，跳转到首页，并修改用户数据
      if (result) {
        // 如果通过验证，就可以拿到用户输入的结果
        const payload = { 
          email: emailVal.value,
          password: passwordVal.value
        }
        console.log(payload)
        // 然后调用store的登录action，发起登录请求
        store.dispatch('loginAndFetch', payload).then(() => {
          // 如果登录成功，那么就调用createMessage给用户提示
          createMessage('登录成功！ 2秒以后跳转首页', 'success')
          setTimeout(() => {
             router.push('/')
          }, 2000)
        }).catch(err => { //在这里加上对错误的处理
          console.log(err)
        })
        // 等发完请求了再清空表单
        // loginFormRef.value.resetForm()
      }
    }
    return {
      emailRules,
      emailVal,
      passwordVal,
      passwordRules,
      onFormSubmit,
      loginFormRef
    }
  }
})
</script>
